<?php

namespace App\Models\Casts;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Episode extends Model
{
    protected $guarded = [];

    public function children()
    {
        return $this->hasMany(Episode::class, 'parent_id', 'id');
    }

    public function parent()
    {
        return $this->belongsTo(Episode::class, 'parent_id', 'id');
    }

    public function category()
    {
        return $this->belongsTo('App\Models\Casts\Category');
    }

    static function get_episodes($request)
    {
        return self::with([
            'children' => function ($query) {
                $query->orderBy('sort_order');
            },
        ])->where('category_id', $request->category_id)->where('parent_id', 0)
            ->orderBy('sort_order')->get();
    }

    /**
     * 排序
     * @param $id
     * @param $parent_id
     * @param $sort_order
     */
    static function sort_order($id, $parent_id, $sort_order)
    {
        $category = self::find($id);
        $category->sort_order = $sort_order;
        $category->parent_id = $parent_id;
        $category->save();
    }

    /**
     * 检查是否有子栏目
     */
    static function check_children($id)
    {
        $episode = self::with('children')->find($id);
        if ($episode->children->isEmpty()) {
            return true;
        }
        return false;
    }
}
